package com.ss.android.article.common.page;

import android.os.Handler;
import android.os.Looper;

import com.bytedance.common.utility.b.ThreadPlusThreadFactory;
import com.bytedance.retrofit2.Call;
import com.bytedance.retrofit2.Callback;
import com.bytedance.retrofit2.ResponseWrapper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;

public abstract class PageList implements Callback {
    public List mItems = new ArrayList();
    public final List<PageListObserver> mObservers = new ArrayList();
    public boolean mHasMore = true;
    public boolean mLoading;
    public Object mLatestPage;
    private boolean mInvalidated;
    private Call mPendingCall;

    static {
        Executors.newSingleThreadExecutor(new ThreadPlusThreadFactory("PageList"));
        new Handler(Looper.getMainLooper());
    }

    public final void load() {
        if (!this.mLoading && ((this.mHasMore) || (this.mInvalidated))) {
            Call v0 = this.onCreateCall();
            this.mLoading = true;
            this.mPendingCall = v0;
            boolean v1 = this.isFirstPageLoading();
            Iterator v2 = this.mObservers.iterator();
            while (v2.hasNext()) {
                ((PageListObserver) v2.next()).onStartLoading(v1, false);
            }

            this.mPendingCall.enqueue(this);
            System.currentTimeMillis();
        }
    }

    public final void onCacheResponse(ResponseWrapper response) {
        this.onLoadCompleted(response.body);
    }

    public abstract void onLoadItemFromResponse(Object arg1, List arg2);

    public final void onErrorResponse(Throwable throwable) {
        boolean v1 = this.isFirstPageLoading();
        this.mLoading = false;
        this.mInvalidated = false;
        this.mPendingCall = null;
        Iterator v2 = this.mObservers.iterator();
        while (v2.hasNext()) {
            ((PageListObserver) v2.next()).onError(v1, throwable);
        }
    }

    public abstract boolean getHasMoreFromResponse(Object arg1);

    public final void onLoadCompleted(Object arg5) {
        boolean v1 = this.isFirstPageLoading();
        if (arg5 != null) {
            this.mHasMore = this.getHasMoreFromResponse(arg5);
            this.onLoadItemFromResponse(arg5, this.mItems);
            this.mLatestPage = arg5;
            Iterator v2 = this.mObservers.iterator();
            while (v2.hasNext()) {
                ((PageListObserver) v2.next()).onFinishLoading(v1, false);
            }
        }

        this.mLoading = false;
        this.mInvalidated = false;
        this.mPendingCall = null;
    }

    public final void refresh() {
        this.mInvalidated = true;
        this.load();
    }

    public abstract Call onCreateCall();

    public final boolean isFirstPageLoading() {
        return this.mLatestPage == null || (this.mInvalidated);
    }
}

